// Tags: Fully Backpack, Multi Backpack
#include <algorithm>
#include <cctype>
#include <cstdio>

template <typename T>
inline T &read(T &x) {
  x = 0;
  bool f = false;
  short ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = true;
    ch = getchar();
  }
  while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ '0'), ch = getchar();
  if (f) x = -x;
  return x;
}

const int N = 1e3 + 5;
int n, T, sthh, stmm, enhh, enmm, f[N], q[N], id[N];

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen64("/tmp/CodeTmp/testdata.in", "r", stdin);
  freopen64("/tmp/CodeTmp/testdata.out", "w", stdout);
#else
  freopen("P1833 樱花.in", "r", stdin);
  freopen("P1833 樱花.out", "w", stdout);
#endif
#endif

  scanf("%d:%d %d:%d %d", &sthh, &stmm, &enhh, &enmm, &n);
  T = enhh * 60 + enmm - sthh * 60 - stmm;
  for (int i = 1, t, c, p; i <= n; ++i) {
    read(t), read(c), read(p);
    if (p == 0) {
      for (int j = t; j <= T; ++j) f[j] = std::max(f[j], f[j - t] + c);
    } else {
      int can_use = std::min(p, T / t);
      for (int j = 0; j < t; ++j) {
        int l = 1, r = 0;
        int all = (T - j) / t;
        for (int k = 0; k <= all; ++k) {
          int tmp = f[j + k * t] - k * c;
          while (l <= r && tmp >= q[r]) --r;
          q[++r] = tmp, id[r] = k;
          while (l <= r && id[l] + can_use < k) ++l;
          f[j + k * t] = std::max(f[j + k * t], q[l] + k * c);
        }
      }
    }
  }
  int ans = 0;
  for (int i = 1; i <= T; ++i) ans = std::max(ans, f[i]);
  printf("%d", ans);
  return 0;
}